package com.itheima.Servlet;

import com.itheima.Servlet.util.studentIDUtil;
import com.itheima.domain.Student;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
@WebServlet("/stu/addStudentServlet")
public class addStudent extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //使用map集合可以获得所有的用户信息  来多少添加多少 灵活方便
        Map<String, String[]> map = req.getParameterMap();
        Student stu = new Student();
        try {
            BeanUtils.populate(stu,map);
        }
         catch (Exception e) {
            e.printStackTrace();
        }

        ServletContext context = getServletContext();
        String id = studentIDUtil.getId(context);
        stu.setSid(id);


        //把数据写进web目录下的stu.txt文件中 因为linux系统没有盘符 所以写在web目录下可以防止跨系统时造成服务器错误
        String realPath = getServletContext().getRealPath("/stu.txt");
                                                                //向stu.txt里写数据时 一定要保证开启续写模式了
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(realPath,true),"UTF-8"));
        bw.write(stu.toString());
        bw.newLine();
        bw.flush();
        bw.close();


        /*
        跳转页面 定时刷新
        resp.setHeader("Refresh","2;URL=/stu/index.html");
        resp.getWriter().write("添加成功!2秒后自动跳转到首页...");*/
        //重定向到查看页面
        resp.sendRedirect(req.getContextPath()+"/stu/findAllStudent");



    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
